package club.gskj.gulimall.product.service.impl;

import club.gskj.common.constant.ProductConstant;
import club.gskj.gulimall.product.dao.AttrAttrgroupRelationDao;
import club.gskj.gulimall.product.dao.AttrGroupDao;
import club.gskj.gulimall.product.dao.CategoryDao;
import club.gskj.gulimall.product.entity.AttrAttrgroupRelationEntity;
import club.gskj.gulimall.product.entity.AttrGroupEntity;
import club.gskj.gulimall.product.entity.CategoryEntity;
import club.gskj.gulimall.product.service.CategoryService;
import club.gskj.gulimall.product.vo.AttrGroupRelationVo;
import club.gskj.gulimall.product.vo.AttrRespVo;
import club.gskj.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.Query;

import club.gskj.gulimall.product.dao.AttrDao;
import club.gskj.gulimall.product.entity.AttrEntity;
import club.gskj.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void save(AttrVo attr) {
        // 先保存 attrEntity
        AttrEntity attrEntity = new AttrEntity();
        // 处理属性Copy
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存基本信息
        this.baseMapper.insert(attrEntity);

        // 判断attr_type类型，销售类型不需要保存关联组信息
        if (attr.getAttrGroupId() != null && attr.getAttrType() != null && attr.getAttrType() == (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            // 属性分组id
            Long attrGroupId = attr.getAttrGroupId();
            attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);

            // 属性id
            Long attrId = attrEntity.getAttrId();
            attrAttrgroupRelationEntity.setAttrId(attrId);
            // 保存关联信息
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Long catelogId, Map<String, Object> params, String pathType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(pathType) && pathType.equals("sale")) {
            queryWrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        } else {
            queryWrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }

        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            // attr_id or  attr_name
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or()
                        .like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);

        // 再次处理数据，返回AttrRespVo
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> attrRespVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            // 通过属性id 查询  分组id
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

            if (attrAttrgroupRelationEntity != null) {
                Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                // 查询分组名称

                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null) {
                    String attrGroupName = attrGroupEntity.getAttrGroupName();
                    attrRespVo.setGroupName(attrGroupName);
                }
            }

            // 根据分类id查询分类名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                String categoryEntityName = categoryEntity.getName();
                attrRespVo.setCateLogName(categoryEntityName);
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    // 放入缓存中
    @Cacheable(value = "attr", key = "'attrInfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();

        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 判断只有基本属性，才查询并设置分组、分类信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            // 分组id
            if (attrAttrgroupRelationEntity != null) {
                Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                // 查询分组名称
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null) {
                    String attrGroupName = attrGroupEntity.getAttrGroupName();
                    attrRespVo.setGroupName(attrGroupName);
                    attrRespVo.setAttrGroupId(attrGroupId);
                }
            }

            //分类path
            Long catelogId = attrEntity.getCatelogId();
            Long[] cateLogPath = categoryService.getCateLogPath(catelogId);
            attrRespVo.setCatelogPath(cateLogPath);

            CategoryEntity categoryEntity = categoryService.getById(catelogId);
            if (categoryEntity != null) {
                String categoryEntityName = categoryEntity.getName();
                attrRespVo.setCateLogName(categoryEntityName);
            }
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttrVo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.baseMapper.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 处理关联表数据一致性
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());

            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            // 如果
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> ListRelationAttr(Long groupId) {
        List<AttrAttrgroupRelationEntity> entitiesList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", groupId));

        // 获取所有 attrId集合
        List<Long> collect = entitiesList.stream().map((entity) -> {
            Long attrId = entity.getAttrId();
            return attrId;
        }).collect(Collectors.toList());

        if (collect == null || collect.size() == 0) {
            return null;
        }
        // 根据ids 批量查询
        List<AttrEntity> attrEntityList = this.baseMapper.selectBatchIds(collect);
        return attrEntityList;
    }

    @Override
    public void deleteAttrRelations(AttrGroupRelationVo[] vos) {

        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((itme) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrId(itme.getAttrId());
            entity.setAttrGroupId(itme.getAttrGroupId());
            return entity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchAttrRelations(collect);
    }

    @Override
    public PageUtils ListNotRelationAttr(Long groupId, Map<String, Object> params) {

        // 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 当前分组只能关联别的分组没有引用的属性
        // 当前分类下的其他分组
        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<Long> groupIds = groups.stream().map((item) -> item.getAttrGroupId()).collect(Collectors.toList());

        // 查询这些分组关联的属性id
        List<AttrAttrgroupRelationEntity> attrGroups = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));

        List<Long> attrIds = attrGroups.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        // 只查询 基本类型属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }

        //关键词查询
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(query -> {
                query.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 查询其他属性列表排除已关联的属性
        IPage<AttrEntity> attrEntityIPage =
                this.baseMapper.selectPage(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(attrEntityIPage);
    }

    @Override
    public List<Long> listSearchAttrIds(List<Long> attrIds) {
        // SELECT attr_id FROM `pms_attr` WHERE attr_id IN() AND search_type = '1'
        return this.baseMapper.listSearchAttrIds(attrIds);
    }
}
